package com.wy.mavenUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class DependenceServiceImpl implements DependenceService {
    /**
     * 使用完整路径执行Maven命令
     *
     * @param pomPath             pom.xml的完整路径
     * @param dependencyOutputDir 输出目录的完整路径
     */
    public void handleWithFullPath(String pomPath, String dependencyOutputDir) throws IOException, InterruptedException {
        checkPath(pomPath);
        checkPath(dependencyOutputDir);
        ProcessBuilder processBuilder = new ProcessBuilder(
                MVN_PATH,
                "dependency:copy-dependencies",
                "-DoutputDirectory=" + dependencyOutputDir,
                "-DincludeScope=runtime",
                "-DincludeTransitiveDependencies=true",
                "-f", pomPath
        );
        executeCommand(processBuilder);
    }

    /**
     * 在项目根目录执行Maven命令
     *
     * @param projectDir 项目根目录
     */
    public void handleInProjectRoot(String projectDir) throws IOException, InterruptedException {
        checkPath(projectDir);
        ProcessBuilder processBuilder = new ProcessBuilder(
                MVN_PATH,
                "dependency:copy-dependencies",
                "-DoutputDirectory=lib",
                "-DincludeScope=runtime",
                "-DincludeTransitiveDependencies=true"
        );

        // 设置工作目录为项目根目录
        processBuilder.directory(new File(projectDir));
        executeCommand(processBuilder);
    }

    /**
     * 执行Maven命令的通用方法
     */
    static void executeCommand(ProcessBuilder processBuilder) throws IOException, InterruptedException {
        // 重定向错误流到标准输出
        processBuilder.redirectErrorStream(true);
//        mvn dependency:copy-dependencies -DoutputDirectory=C:\Users\wy\Desktop\1111111\lib2 -DincludeScope=runtime -DincludeTransitiveDependencies=true -f D:\gitee_versionControllerProject\basic-knowledge\30项目打包方式\projectPackage\pom.xml
        // 启动进程
        Process process = processBuilder.start();

        // 读取输出
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }

        // 等待进程完成
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("Maven 命令执行失败，退出码: " + exitCode);
        }
    }

    /**
     * 检查文件路径是否正确
     *
     * @param filePath 文件路径
     */
    static void checkPath(String filePath) {
        String trim = filePath.trim();
        if (trim.contains(" ")) {
            throw new RuntimeException("文件路径异常,文件路径不可以包含空格 " + filePath);
        }
    }
}
